package com.example.administrator.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

/**
 * Created by Administrator on 2016/11/29.
 */
public class ZhuCeActivity extends MainActivity{

    private EditText iput_nuber;
    private EditText text_yanzheng;
    private EditText input_pwd;
    private Button bu_yanzheng;
    private Button bu_zhuche;
    String code;//验证码
    private TimeCount time;
    private String dianhua;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zhu_ce_layout);
        input_pwd = (EditText) findViewById(R.id.sheZhiMiMa);
        iput_nuber = (EditText) findViewById(R.id.phoneNumber);
        text_yanzheng = (EditText) findViewById(R.id.yanZhengMaText);
        bu_yanzheng = (Button) findViewById(R.id.yanZhengMaButton);
        bu_zhuche = (Button) findViewById(R.id.queRenZhuCeBtn);
        time = new TimeCount(60000, 1000);
        if (isNetworkAvailable(this)){
            Toast.makeText(getApplicationContext(), "当前有可用网络！", Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getApplicationContext(), "当前没有可用网络！", Toast.LENGTH_LONG).show();
        }

        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bitmap bitmap = (Bitmap) msg.obj;
            }
        };
//        bu_zhuche.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String yanzhen = text_yanzheng.getText().toString();
//                int yan =Integer.valueOf(yanzhen);
//                code = code.trim();
//                int str2 = 0;
//                if(code != null && !"".equals(code)) {
//                    for (int i = 0; i < code.length(); i++) {
//                        if (code.charAt(i) >= 48 && code.charAt(i) <= 57) {
//                            str2 += code.charAt(i);
//                        }
//                    }
//
//                }
//                if (yan != str2){
//                    Toast.makeText(getApplicationContext(),"验证码不正确",Toast.LENGTH_SHORT).show();
//                }else {
//                    //1 创建HTTPClient对象
//                    HttpClient httpClient = new DefaultHttpClient();
//                    dianhua = iput_nuber.getText().toString().trim();
//                    String mi =  input_pwd.getText().toString();
//                    //http://api.zhaibao.cn/sendRegCode?
//                    HttpGet get = new HttpGet("http://api.zhaibao.cn/sendRegCode?mobile=" + dianhua + "&password="+mi+"version=1.0&device=2");
//                    try {
//                        //3. 使用httpclient对象去执行get对象
//                        HttpResponse response = httpClient.execute(get);
//
//                        //4. 判断请求结果  200是成功code
//                        if (response.getStatusLine().getStatusCode() == 200) {
//                            //1. 拿到http的实体（另外还有一个头）
//                            HttpEntity entity = response.getEntity();
//                            //服务器返回的字符串
//                            String resault = EntityUtils.toString(entity);
//                            JSONObject jsonObject = new JSONObject(resault);
//                            String suc = jsonObject.getString("success");//{"success":{"message":"验证码已发送到您的手机，请查看.code:698981","code":0}}
//                            JSONObject sucJson = new JSONObject(suc);//{"message":"验证码已发送到您的手机，请查看.code:698981","code":0}
//                            String msg = sucJson.getString("message");//{"message":"，验证码已发送到您的手机请查看.code:698981","code":0}
//                            code = sucJson.getString("code");//验证码已发送到您的手机，请查看.code:698981
//                            int iCode = sucJson.getInt("code");
//                            Log.d("", "");
//
//                        } else {
//                        }
//                    } catch (Exception e) {
//                    }
//                }
//
//            }
//
//        });
        //获取验证码
        bu_yanzheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
//                            子线程的开始
                        downloadImage();
                        time.start();
                    }
                }.start();
            }
        });

    }


    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {//计时完毕时触发
            text_yanzheng.setText("重新验证");
            text_yanzheng.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            text_yanzheng.setClickable(false);
            text_yanzheng.setText(millisUntilFinished / 1000 + "秒");
        }
    }


    private void downloadImage() {
        //1 创建HTTPClient对象
        HttpClient httpClient = new DefaultHttpClient();
        //2. 创建GET对象
        dianhua = iput_nuber.getText().toString();
//        if (dianhua.equals("")) {
//            Toast.makeText(this, "号码不能为空", 0).show();
//        } else if (dianhua.length() != 11) {
//            Toast.makeText(this, "号码必须为11位哦！！！", 0).show();
//        } else {

            Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();
            //http://api.zhaibao.cn/checkRegCode?
            HttpGet get = new HttpGet("http://api.zhaibao.cn/sendRegCode?mobile=" + dianhua + "&version=1.0&device=2");
            try {
                //3. 使用httpclient对象去执行get对象
                HttpResponse response = httpClient.execute(get);

                //4. 判断请求结果  200是成功code
                if (response.getStatusLine().getStatusCode() == 200) {
                    //1. 拿到http的实体（另外还有一个头）
                    HttpEntity entity = response.getEntity();

                    //服务器返回的字符串
                    String resault = EntityUtils.toString(entity);

                    JSONObject jsonObject = new JSONObject(resault);
                    String suc = jsonObject.getString("success");//{"success":{"message":"验证码已发送到您的手机，请查看.code:698981","code":0}}
                    JSONObject sucJson = new JSONObject(suc);//{"message":"验证码已发送到您的手机，请查看.code:698981","code":0}
                    String msg = sucJson.getString("message");//{"message":"，验证码已发送到您的手机请查看.code:698981","code":0}
                    code = sucJson.getString("code");//验证码已发送到您的手机，请查看.code:698981
                    int iCode = sucJson.getInt("code");
                    Log.d("", "");


                } else {
                }
            } catch (Exception e) {
            }
        }

//    }



    public boolean isNetworkAvailable(Activity activity)
    {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null)
        {
            return false;
        }
        else
        {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
